<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="record.content_id?$t('编辑'):$t('添加')" append-to-body :v-if="dialogVisible" :visible.sync="dialogVisible" width="500px" top="5vh" @close='close'>
    <div class="dialogContentBoxMaxHeight90">
      <el-form ref="form" :inline="true" :model="record" label-width="120px" :rules="rules" label-position="left" style="margin:0 30px;">
        <el-form-item :label="$t('特征名称')" class="opcuaForm" prop="content_name">
          <el-input v-emoji v-model.trim="record.content_name" class="customLength" size='small' id="content-dialog-content_name"></el-input>
        </el-form-item>
        <el-form-item :label="$t('匹配模式')" class="opcuaForm" prop="match_type">
          <el-select class="customLength" v-model="record.match_type" @change="matchTypeChange" size='small' filterable>
            <el-option v-for="(value, key) in matchTypeList" :key="key" :label="$t(value)" :value="key" :id="`content-dialog-match_type${key}`">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('偏移位置')" class="opcuaForm" prop="offset" key="offset">
          <el-input v-emoji @input="handleInput" v-model.trim="record.offset" class="customLength" size='small' id="content-dialog-offset"></el-input>
        </el-form-item>
        <el-form-item label=" " class="opcuaForm" v-if="record.match_type === 'string'" prop="case" key="case">
          <el-checkbox v-model="record.case" true-label='true' false-label='false' :disabled='record.regular === "true"'>{{$t('区分大小写')}}</el-checkbox>
          <el-checkbox v-model="record.regular" true-label='true' false-label='false' :disabled='record.case === "true"'>{{$t('启用正则')}}</el-checkbox>
        </el-form-item>
        <el-form-item label=" " class="opcuaForm" v-if="record.match_type === 'byte'" prop="hex" key="hex">
          <el-checkbox v-model="record.hex" true-label='true' false-label='false'>{{$t('16进制')}}</el-checkbox>
        </el-form-item>
        <el-form-item :label="$t('匹配特征')" class="opcuaForm" prop="match_content" key="match_content">
          <template slot="label">{{$t('匹配特征')}}
            <el-tooltip class="item" v-if="record.match_type === 'byte'" effect="light" :content="$t('以逗号(,)分割的形式，不开启16进制情况下，只允许数字，取值范围[0-255]。16进制则必须有0x前缀，取值[0x00-0xFF]，不限制大小写。')" placement="top">
              <i class="el-icon-warning-outline" style="color:#E6A23C;font-size:16px;"></i>
            </el-tooltip>
          </template>
          <el-input v-emoji v-model.trim="record.match_content" class="customLength" id="content-dialog-match_content" size='small' @input="matchContentChange" :autosize="{ minRows: 4 }" type="textarea" @keydown.native="handleKeyCode($event)"></el-input>
        </el-form-item>
        <el-form-item :label="$t('匹配长度')" class="opcuaForm" prop="content_len" key="content_len" v-if="record.regular !== 'true'">
          {{ record.content_len }}
          <!-- <el-input v-emoji v-model.trim="record.content_len" class="customLength" :disabled='true' size='small'></el-input> -->
        </el-form-item>
        <div>
          <el-form-item class="opcuaForm">
            <template slot="label">
              <span>{{$t('总长度')}}</span>
              <el-tooltip effect="light" :content="$t('特征偏移位置加上匹配特征的字符串长度之和应小于1450')" placement="top">
                <i class="el-icon-warning-outline" style="color:#FF0000;font-size:16px;vertical-align: text-bottom;"></i>
              </el-tooltip>
            </template>
            {{lengthMax}}
          </el-form-item>
        </div>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" id="content-dialog-submit">{{$t('确 定')}}</el-button>
      <el-button @click="close" id="content-dialog-cancel">{{$t('取 消')}}</el-button>
    </span>

  </el-dialog>
</template>
<script>
import Template from '../../../../access/template/Template.vue'
import ruleArray from '../../ruleArray'
export default {
  components: { Template },
  name: 'ContentDialog',
  data () {
    var validateValue = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    var validateValueRange = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (isNaN(Number(value))) {
        callback(new Error(this.$t('只能输入数字')))
      } else if (!this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (Number(value) < 0 || Number(value) >= 1450) {
        callback(new Error(this.$t('输入范围0-1449')))
      } else {
        callback()
      }
    }
    var validateMatchContent = (rule, value, callback) => {
      let zhStr = /[^\u4E00-\u9FA5]/g
      var reg = /^[0-9,]+$/
      var reg16 = /^[0-9A-Fa-fx,]+$/
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (this.record.match_type === 'string') {
        if (!String(value).match(zhStr) || (String(value).match(zhStr).length !== String(value).length)) {
          callback(new Error(this.$t('不能输入中文')))
        } else if (value.length > 1450) {
          callback(new Error(this.$t('长度不能超过1450')))
        }
      } else if (this.record.match_type === 'byte') {
        if (this.record.hex === 'true') {
          if (!reg16.test(value)) {
            callback(new Error(this.$t('只能输入十六进制数和逗号')))
          } else if (value.split(',').length > 1450) {
            callback(new Error(this.$t('长度不能超过1450')))
          } else {
            for (let item of value.split(',')) {
              if (!item.match(/^0x/)) {
                callback(new Error(this.$t('请输入十六进制数')))
              } else if (item === '0x') {
                callback(new Error(this.$t('输入范围为0x00-0xFF')))
              } else if (item.length > 4) {
                callback(new Error(this.$t('数字范围为0x00-0xFF')))
              }
            }
          }
        } else {
          if (!reg.test(value)) {
            callback(new Error(this.$t('只能输入数字和逗号')))
          } else if (value.split(',').length > 1450) {
            callback(new Error(this.$t('长度不能超过1450')))
          } else {
             const arrSplit = value.split(',');
             const flag = arrSplit.every(item=>item);
             if(!flag) {
              callback(new Error(this.$t('逗号间不能为空')))
            }else {
              for (let item of value.split(',')) {
              if (Number(item) > 255) {
                callback(new Error(this.$t('数字范围为0-255')))
              }
            }
            }
            
          }
        }
      }
      callback()
    }
    return {
      dialogVisible: false,
      record: {
        case: 'false',
        content_id: null,
        content_len: 0,
        content_name: '',
        hex: 'false',
        match_content: '',
        match_type: 'string',
        offset: '',
        regular: 'false'
      },
      recordCopy: {
        case: 'false',
        content_id: null,
        content_len: 0,
        content_name: '',
        hex: 'false',
        match_content: '',
        match_type: 'string',
        offset: '',
        regular: 'false'
      },
      matchTypeList: ruleArray.matchTypeList,
      rules: {
        content_name: [{ required: false, validator: validateValue, trigger: 'blur' }],
        match_content: [{ required: false, validator: validateMatchContent, trigger: 'blur' }],
        offset: [{ required: false, validator: validateValueRange, trigger: 'blur' }],
        // content_len: [{ required: false, validator: validateValueRange, trigger: 'blur' }]
      }
    }
  },
  computed:{
    lengthMax() {
      return  Number(this.record.offset) + this.record.match_content.length
    }
  },
  watch: {
    'record.match_content': {
      handler (newVal) {
        this.record.match_content = newVal.replace(/[\r\n]/g, '')
      },
      immediate: true
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      if (data) {
        this.record = Object.assign(this.record, data)
      }
    },
    handleInput(value) {
      const valueTemp = value.trim()
      if(valueTemp) {
        if(isNaN(Number(valueTemp))) {
        this.record.offset = valueTemp;
      }else {
        this.record.offset = Number(valueTemp)
      }
      }else {
        this.record.offset = valueTemp;
      }
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          var formData = JSON.parse(JSON.stringify(this.record))
          if(this.record.match_type) {
              if(this.lengthMax >= 1450){
                this.$messages.error(this.$t('特征偏移位置加上匹配特征的字符串长度之和应小于1450'))
              }else {
                if (formData.content_id) {
              this.$emit('editContentRows', formData)
            } else {
              this.$emit('addContentRows', formData)
            }
              }
          }else {
            if (formData.content_id) {
              this.$emit('editContentRows', formData)
            } else {
              this.$emit('addContentRows', formData)
            }
          }
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.form.resetFields()
    },
    isInteger (value) {
      return (!isNaN(value) && (parseInt(value).toString().length === String(Number(value)).length))
    },
    handleKeyCode (event) {
      if (event.keyCode === 13) {
        event.preventDefault() // 阻止浏览器默认换行操作
        return false
      }
    },
    matchTypeChange () {
      this.record.offset = ''
      this.record.case = 'false'
      this.record.regular = 'false'
      this.record.hex = 'false'
      this.record.match_content = ''
      this.record.content_len = 0
    },
    matchContentChange (data) {
      if (this.record.match_type === 'string') {
        this.record.content_len = this.record.match_content.trim() ? this.record.match_content.trim().length : 0
      } else if (this.record.match_type === 'byte') {
        this.record.content_len = this.record.match_content ? this.trimSpace(this.record.match_content.split(',')).length : 0
      }
    },
    trimSpace (array) {
      for (var i = 0; i < array.length; i++) {
        if (array[i] === '' || array[i] == null || typeof (array[i]) === 'undefined') {
          array.splice(i, 1)
          i = i - 1
        }
      }
      return array
    }
  }
}
</script>
<style>
.customLength {
  width: 250px;
}
</style>
